import {Button, Form, Input, message, Popconfirm, Select, Switch, Table} from "antd";
import React, {useEffect, useState, useTransition} from "react";
import {useNavigate, useParams} from "react-router-dom";
import {ArticleDataType} from "../../util/publicType";
import {ColumnsType} from "antd/es/table";
import {articleList, articleUpdateGrounding, articleUpdateRecommend, delArticle} from "../../api";
import {AxiosResponse} from "axios";
import {setNullData} from "../../util";
import {CheckOutlined, CloseOutlined} from "@ant-design/icons";
import RequestLoading from "../../components/RequestLoading";

type MetaType =  {
    currentPage: number,
    lastPage: number,
    perSize: number,
    total: number
}

// 所有文章页面，变化的只有id也就是数据不同
const Article = () => {
    useEffect(()=>{
        const form:{name:string,age:number} = {
            name:"123",
            age:23
        };
        console.log(form['name'])
    },[

    ])
    const [loading, setTransition] = useTransition();
    // 搜索表单
    const [searchForm] = Form.useForm();
    // 分页
    const [page, setPage] = useState<number>(1);
    // 当前页数
    const [size, setSize] = useState<number>(15);
    // 名字搜索
    const [name, setName] = useState<string | null>(null);
    // 上架筛选
    const [grounding, setGrounding] = useState<number | null>(null);
    // 字典id
    const [dictId, setDictId] = useState<string>("");
    // 路由
    const n = useNavigate();
    // 分页数据
    const [meta, setMeta] = useState<MetaType>({
        currentPage: 1,
        lastPage: 1,
        perSize: 1,
        total: 1
    });

    // 当前分类id
    const {id} = useParams();

    // 表数据
    const [data, setData] = useState<ArticleDataType[]>([]);

    const searchFinish = (v: { name: string, grounding: number }) => {
        if (!v.name) {
            setName(null)
        } else {
            setName(v.name)
        }
        if (!v.grounding) {
            setGrounding(null)
        } else {
            setGrounding(v.grounding)
        }
        getData(page, size, v.name, v.grounding);
    }

    // 表头
    const columns: ColumnsType<ArticleDataType> = [
        {
            title: "封面",
            dataIndex: "cover_url",
            key: "cover_url",
            align: "center",
            render: (v: string) => {
                return (
                    <div style={{width: "50px", height: "50px", margin: "0 auto"}}>
                        <img src={v} width={50} height={50} alt="" style={{objectFit: "contain"}}/>
                    </div>
                )
            }
        },
        {
            title: "文章名字",
            dataIndex: "name",
            key: "name",
            align: "center",
            width: "18%"
        },
        {
            title: "编辑者",
            dataIndex: "username",
            key: "username",
            align: "center"
        },
        {
            title: "阅读数",
            dataIndex: "visit_num",
            key: "visit_num",
            align: "center"
        },
        {
            title: "首页推荐",
            dataIndex: "recommend",
            key: "recommend",
            align: "center",
            render: (v: number, record: ArticleDataType) => {
                return (
                    <Switch
                        checkedChildren={<CheckOutlined/>}
                        unCheckedChildren={<CloseOutlined/>}
                        defaultChecked={!!v}
                        onChange={(v: boolean) => {
                            articleUpdateRecommend(record.id, {recommend: v ? 1 : 0}).then(async () => {
                                getData(page, size, name, grounding);
                                await message.success(v ? "已推荐到首页" : "已取消推荐");
                            }, err => message.error(err))
                        }}
                    />
                )
            }
        },
        {
            title: "是否上架",
            dataIndex: "grounding",
            key: "grounding",
            align: "center",
            render: (v: number, record: ArticleDataType) => {
                return (
                    <Switch
                        checkedChildren={<CheckOutlined/>}
                        unCheckedChildren={<CloseOutlined/>}
                        defaultChecked={!!v}
                        onChange={(v: boolean) => {
                            articleUpdateGrounding(record.id, {grounding: v ? 1 : 0}).then(async () => {
                                getData(page, size, name, grounding);
                                await message.success(v ? "已上架" : "已取消上架");
                            }, err => message.error(err))
                        }}
                    />
                )
            }
        },
        // {
        //     title: "所属区域",
        //     dataIndex: "region_name",
        //     key: "region_name",
        //     align: "center"
        // },
        {
            title: "操作",
            dataIndex: "id",
            key: "id",
            align: "center",
            render: (v: string, record: ArticleDataType) => {
                return (
                    <div>
                        <Button type="primary" onClick={() => editClick(v)}
                                style={{marginRight: "10px"}}>编辑</Button>
                        <Popconfirm
                            title="删除操作"
                            description={`确定删除${record.name}文章吗？`}
                            onConfirm={() => delClick(v)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button type="primary" danger>删除</Button>
                        </Popconfirm>
                    </div>
                )
            }
        }
    ]
    // 请求
    const getData = (page: number, size: number, name: string | null = null, grounding: number | null = null) => {
        setTransition(() => {
            articleList(page, size, name, grounding, (id as string)).then((r: AxiosResponse) => {
                let {data, meta, type_id} = r.data.data;
                setDictId(type_id);
                setMeta(meta);
                data = data.map((v: ArticleDataType) => {
                    return {
                        ...v,
                        key: v.id,
                        cover_url: v.cover.path,
                        region_name: setNullData(v.region_name, "暂无"),
                        visit_num: setNullData(v.visit_num, "0")
                    }
                });
                setData(data);
            })
        })
    }

    // 当文献类型变化时监听执行
    useEffect(() => {
        setPage(1);
        setSize(15);
        setName(null);
        setGrounding(null);
        // 重新请求
        getData(page, size);
        // 清除搜索条件
        searchForm.resetFields();
    }, [id]);

    // 添加
    const addClick = () => {
        n(`/article/create/${dictId}`);
    }

    // 编辑
    const editClick = (id: string) => {
        console.log(meta['total'])
        n(`/article/update/${id}`)
    }

    // 刪除
    const delClick = (id: string) => {
        delArticle(id).then(async () => {
            getData(page, size, name, grounding)
            message.success("刪除成功");
        })
    }

    return (
        <>
            <div style={{padding: "30px 0"}}>
                <Form form={searchForm} layout="inline" onFinish={searchFinish}>
                    <Form.Item
                        name="name"
                        label="文章名字"
                    >
                        <Input placeholder="请输入分类名字"/>
                    </Form.Item>
                    <Form.Item
                        name="grounding"
                        label="上架状态"
                    >
                        <Select
                            style={{width: "200px"}}
                            placeholder="请选择分类"
                            options={[
                                {
                                    label: "未上架",
                                    value: "0",
                                },
                                {
                                    label: "已上架",
                                    value: "1"
                                }
                            ]}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" style={{marginRight: "10px"}} htmlType="submit">
                            搜索
                        </Button>
                        <Button type="primary" htmlType="reset" style={{marginRight: "10px"}}>
                            重置
                        </Button>
                        <Button type="primary" onClick={addClick}>
                            新建
                        </Button>
                    </Form.Item>
                </Form>
            </div>
            {
                loading ? (<RequestLoading/>) : (
                    <Table columns={columns} dataSource={data} pagination={
                        {
                            current: meta.currentPage,
                            defaultCurrent: meta.currentPage,
                            defaultPageSize: meta.perSize,
                            pageSize: meta.perSize,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            showTotal: (t: number) => `总条数${t}`,
                            total: meta.total,
                            onChange: (page: number, perSize: number) => {
                                setPage(page)
                                setSize(perSize);
                                getData(page, perSize, name, grounding);
                            }
                        }
                    }/>
                )
            }
        </>
    )
}

export default Article;
